/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhongJinTao
 * Date: 2024-01-06
 * Time: 14:48
 */
public class MyQueue implements IQueue{
    class ListNode {
        public int value;
        public ListNode prev;
        public ListNode next;
        public ListNode(int value) {
            this.value = value;
        }
    }
    ListNode head;
    ListNode last;
    int usedSize;

    @Override
    public boolean offer(int x) {
        ListNode node = new ListNode(x);
        if(head == null) {
            head = node;
            last = node;
        } else {
            last.next = node;
            node.prev = last;
            last = last.next;
        }
        usedSize++;
        return true;
    }

    @Override
    public int poll() {
        if(head == null) {
            //队列为空，出不了队列，抛异常
            throw new EmptyException("队列为空");
        }
        if(head.next == null) {
            int retValue = head.value;
            last = null;
            head = null;
            usedSize--;
            return retValue;
        }
        int retValue = head.value;
        ListNode nodeNext = this.head.next;
        head.next = null;
        nodeNext.prev = null;
        head = nodeNext;
        usedSize--;
        return retValue;
    }

    @Override
    public int peek() {
        if(head == null) {
            //队列为空，出不了队列，抛异常
            throw new EmptyException("队列为空");
        } else {
            int retValue = head.value;
            return retValue;
        }
    }

    @Override
    public int size() {
        return usedSize;
    }

    @Override
    public boolean isEmpty() {
        return this.head == null;
    }
}
